3 namespace Wikimedia\Rdbms
;
5 use InvalidArgumentException
;
8 * Helper class used for automatically marking an IDatabase connection as reusable (once it no
9 * longer matters which DB domain is selected) and for deferring the actual network connection
11 * This uses an RAII-style pattern where calling code is expected to keep the returned reference
12 * handle as a function variable that falls out of scope when no longer needed. This avoids the
13 * need for matching reuseConnection() calls for every "return" statement as well as the tedious
18 * function getRowData() {
19 * $conn = $this->lb->getConnectedRef( DB_REPLICA );
20 * $row = $conn->select( ... );
21 * return $row ? (array)$row : false;
22 * // $conn falls out of scope and $this->lb->reuseConnection() gets called
29 class DBConnRef
implements IDatabase
{
30 /** @var ILoadBalancer */
32 /** @var Database|null Live connection handle */
34 /** @var array|null N-tuple of (server index, group, DatabaseDomain|string) */
36 /** @var int One of DB_MASTER/DB_REPLICA */
45 * @param ILoadBalancer $lb Connection manager for $conn
46 * @param IDatabase|array $conn Database or (server index, query groups, domain, flags)
47 * @param int $role The type of connection asked for; one of DB_MASTER/DB_REPLICA
48 * @internal This method should not be called outside of LoadBalancer
50 public function __construct( ILoadBalancer
$lb, $conn, $role ) {
53 if ( $conn instanceof IDatabase
&& !( $conn instanceof DBConnRef
) ) {
54 $this->conn
= $conn; // live handle
55 } elseif ( is_array( $conn ) && count( $conn ) >= 4 && $conn[self
::FLD_DOMAIN
] !== false ) {
56 $this->params
= $conn;
58 throw new InvalidArgumentException( "Missing lazy connection arguments." );
62 function __call( $name, array $arguments ) {
63 if ( $this->conn
=== null ) {
64 list( $index, $groups, $wiki, $flags ) = $this->params
;
65 $this->conn
= $this->lb
->getConnection( $index, $groups, $wiki, $flags );
68 return $this->conn
->$name( ...$arguments );
72 * @return int DB_MASTER when this *requires* the master DB, otherwise DB_REPLICA
75 public function getReferenceRole() {
79 public function getServerInfo() {
80 return $this->__call( __FUNCTION__
, func_get_args() );
84 * @param bool|null $buffer
86 * @deprecated Since 1.34 Use query batching
88 public function bufferResults( $buffer = null ) {
89 return $this->__call( __FUNCTION__
, func_get_args() );
92 public function trxLevel() {
93 return $this->__call( __FUNCTION__
, func_get_args() );
96 public function trxTimestamp() {
97 return $this->__call( __FUNCTION__
, func_get_args() );
100 public function explicitTrxActive() {
101 return $this->__call( __FUNCTION__
, func_get_args() );
104 public function assertNoOpenTransactions() {
105 return $this->__call( __FUNCTION__
, func_get_args() );
108 public function tablePrefix( $prefix = null ) {
109 if ( $this->conn
=== null && $prefix === null ) {
110 $domain = DatabaseDomain
::newFromId( $this->params
[self
::FLD_DOMAIN
] );
111 // Avoid triggering a database connection
112 return $domain->getTablePrefix();
113 } elseif ( $this->conn
!== null && $prefix === null ) {
114 // This will just return the prefix
115 return $this->__call( __FUNCTION__
, func_get_args() );
117 // Disallow things that might confuse the LoadBalancer tracking
118 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
121 public function dbSchema( $schema = null ) {
122 if ( $this->conn
=== null && $schema === null ) {
123 $domain = DatabaseDomain
::newFromId( $this->params
[self
::FLD_DOMAIN
] );
124 // Avoid triggering a database connection
125 return $domain->getSchema();
126 } elseif ( $this->conn
!== null && $schema === null ) {
127 // This will just return the schema
128 return $this->__call( __FUNCTION__
, func_get_args() );
130 // Disallow things that might confuse the LoadBalancer tracking
131 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
134 public function getLBInfo( $name = null ) {
135 return $this->__call( __FUNCTION__
, func_get_args() );
138 public function setLBInfo( $nameOrArray, $value = null ) {
139 // Disallow things that might confuse the LoadBalancer tracking
140 throw new DBUnexpectedError( $this, "Changing LB info is disallowed to enable reuse." );
143 public function setLazyMasterHandle( IDatabase
$conn ) {
144 // Disallow things that might confuse the LoadBalancer tracking
145 throw new DBUnexpectedError( $this, "Database injection is disallowed to enable reuse." );
148 public function implicitOrderby() {
149 return $this->__call( __FUNCTION__
, func_get_args() );
152 public function lastQuery() {
153 return $this->__call( __FUNCTION__
, func_get_args() );
156 public function lastDoneWrites() {
157 return $this->__call( __FUNCTION__
, func_get_args() );
160 public function writesPending() {
161 return $this->__call( __FUNCTION__
, func_get_args() );
164 public function preCommitCallbacksPending() {
165 return $this->__call( __FUNCTION__
, func_get_args() );
168 public function writesOrCallbacksPending() {
169 return $this->__call( __FUNCTION__
, func_get_args() );
172 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
173 return $this->__call( __FUNCTION__
, func_get_args() );
176 public function pendingWriteCallers() {
177 return $this->__call( __FUNCTION__
, func_get_args() );
180 public function pendingWriteRowsAffected() {
181 return $this->__call( __FUNCTION__
, func_get_args() );
184 public function isOpen() {
185 return $this->__call( __FUNCTION__
, func_get_args() );
188 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
189 return $this->__call( __FUNCTION__
, func_get_args() );
192 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
193 return $this->__call( __FUNCTION__
, func_get_args() );
196 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
197 return $this->__call( __FUNCTION__
, func_get_args() );
200 public function getFlag( $flag ) {
201 return $this->__call( __FUNCTION__
, func_get_args() );
204 public function getProperty( $name ) {
205 return $this->__call( __FUNCTION__
, func_get_args() );
208 public function getDomainID() {
209 if ( $this->conn
=== null ) {
210 $domain = $this->params
[self
::FLD_DOMAIN
];
211 // Avoid triggering a database connection
212 return $domain instanceof DatabaseDomain ?
$domain->getId() : $domain;
215 return $this->__call( __FUNCTION__
, func_get_args() );
218 public function getType() {
219 if ( $this->conn
=== null ) {
220 // Avoid triggering a database connection
221 if ( $this->params
[self
::FLD_INDEX
] === ILoadBalancer
::DB_MASTER
) {
222 $index = $this->lb
->getWriterIndex();
224 $index = $this->params
[self
::FLD_INDEX
];
227 // In theory, if $index is DB_REPLICA, the type could vary
228 return $this->lb
->getServerType( $index );
232 return $this->__call( __FUNCTION__
, func_get_args() );
235 public function fetchObject( $res ) {
236 return $this->__call( __FUNCTION__
, func_get_args() );
239 public function fetchRow( $res ) {
240 return $this->__call( __FUNCTION__
, func_get_args() );
243 public function numRows( $res ) {
244 return $this->__call( __FUNCTION__
, func_get_args() );
247 public function numFields( $res ) {
248 return $this->__call( __FUNCTION__
, func_get_args() );
251 public function fieldName( $res, $n ) {
252 return $this->__call( __FUNCTION__
, func_get_args() );
255 public function insertId() {
256 return $this->__call( __FUNCTION__
, func_get_args() );
259 public function dataSeek( $res, $row ) {
260 return $this->__call( __FUNCTION__
, func_get_args() );
263 public function lastErrno() {
264 return $this->__call( __FUNCTION__
, func_get_args() );
267 public function lastError() {
268 return $this->__call( __FUNCTION__
, func_get_args() );
271 public function affectedRows() {
272 return $this->__call( __FUNCTION__
, func_get_args() );
275 public function getSoftwareLink() {
276 return $this->__call( __FUNCTION__
, func_get_args() );
279 public function getServerVersion() {
280 return $this->__call( __FUNCTION__
, func_get_args() );
283 public function close() {
284 throw new DBUnexpectedError( $this->conn
, 'Cannot close shared connection.' );
287 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
288 if ( $this->role
!== ILoadBalancer
::DB_MASTER
) {
289 $flags |
= IDatabase
::QUERY_REPLICA_ROLE
;
292 return $this->__call( __FUNCTION__
, [ $sql, $fname, $flags ] );
295 public function freeResult( $res ) {
296 return $this->__call( __FUNCTION__
, func_get_args() );
299 public function selectField(
300 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
302 return $this->__call( __FUNCTION__
, func_get_args() );
305 public function selectFieldValues(
306 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
308 return $this->__call( __FUNCTION__
, func_get_args() );
311 public function select(
312 $table, $vars, $conds = '', $fname = __METHOD__
,
313 $options = [], $join_conds = []
315 return $this->__call( __FUNCTION__
, func_get_args() );
318 public function selectSQLText(
319 $table, $vars, $conds = '', $fname = __METHOD__
,
320 $options = [], $join_conds = []
322 return $this->__call( __FUNCTION__
, func_get_args() );
325 public function limitResult( $sql, $limit, $offset = false ) {
326 return $this->__call( __FUNCTION__
, func_get_args() );
329 public function selectRow(
330 $table, $vars, $conds, $fname = __METHOD__
,
331 $options = [], $join_conds = []
333 return $this->__call( __FUNCTION__
, func_get_args() );
336 public function estimateRowCount(
337 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
339 return $this->__call( __FUNCTION__
, func_get_args() );
342 public function selectRowCount(
343 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
345 return $this->__call( __FUNCTION__
, func_get_args() );
348 public function lockForUpdate(
349 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
351 $this->assertRoleAllowsWrites();
353 return $this->__call( __FUNCTION__
, func_get_args() );
356 public function fieldExists( $table, $field, $fname = __METHOD__
) {
357 return $this->__call( __FUNCTION__
, func_get_args() );
360 public function indexExists( $table, $index, $fname = __METHOD__
) {
361 return $this->__call( __FUNCTION__
, func_get_args() );
364 public function tableExists( $table, $fname = __METHOD__
) {
365 return $this->__call( __FUNCTION__
, func_get_args() );
368 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
369 $this->assertRoleAllowsWrites();
371 return $this->__call( __FUNCTION__
, func_get_args() );
374 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
375 $this->assertRoleAllowsWrites();
377 return $this->__call( __FUNCTION__
, func_get_args() );
380 public function makeList( $a, $mode = self
::LIST_COMMA
) {
381 return $this->__call( __FUNCTION__
, func_get_args() );
384 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
385 return $this->__call( __FUNCTION__
, func_get_args() );
388 public function aggregateValue( $valuedata, $valuename = 'value' ) {
389 return $this->__call( __FUNCTION__
, func_get_args() );
392 public function bitNot( $field ) {
393 return $this->__call( __FUNCTION__
, func_get_args() );
396 public function bitAnd( $fieldLeft, $fieldRight ) {
397 return $this->__call( __FUNCTION__
, func_get_args() );
400 public function bitOr( $fieldLeft, $fieldRight ) {
401 return $this->__call( __FUNCTION__
, func_get_args() );
404 public function buildConcat( $stringList ) {
405 return $this->__call( __FUNCTION__
, func_get_args() );
408 public function buildGroupConcatField(
409 $delim, $table, $field, $conds = '', $join_conds = []
411 return $this->__call( __FUNCTION__
, func_get_args() );
414 public function buildSubstring( $input, $startPosition, $length = null ) {
415 return $this->__call( __FUNCTION__
, func_get_args() );
418 public function buildStringCast( $field ) {
419 return $this->__call( __FUNCTION__
, func_get_args() );
422 public function buildIntegerCast( $field ) {
423 return $this->__call( __FUNCTION__
, func_get_args() );
426 public function buildSelectSubquery(
427 $table, $vars, $conds = '', $fname = __METHOD__
,
428 $options = [], $join_conds = []
430 return $this->__call( __FUNCTION__
, func_get_args() );
433 public function databasesAreIndependent() {
434 return $this->__call( __FUNCTION__
, func_get_args() );
437 public function selectDB( $db ) {
438 // Disallow things that might confuse the LoadBalancer tracking
439 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
442 public function selectDomain( $domain ) {
443 // Disallow things that might confuse the LoadBalancer tracking
444 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
447 public function getDBname() {
448 if ( $this->conn
=== null ) {
449 $domain = DatabaseDomain
::newFromId( $this->params
[self
::FLD_DOMAIN
] );
450 // Avoid triggering a database connection
451 return $domain->getDatabase();
454 return $this->__call( __FUNCTION__
, func_get_args() );
457 public function getServer() {
458 return $this->__call( __FUNCTION__
, func_get_args() );
461 public function addQuotes( $s ) {
462 return $this->__call( __FUNCTION__
, func_get_args() );
465 public function addIdentifierQuotes( $s ) {
466 return $this->__call( __FUNCTION__
, func_get_args() );
469 public function buildLike( $param ) {
470 return $this->__call( __FUNCTION__
, func_get_args() );
473 public function anyChar() {
474 return $this->__call( __FUNCTION__
, func_get_args() );
477 public function anyString() {
478 return $this->__call( __FUNCTION__
, func_get_args() );
481 public function nextSequenceValue( $seqName ) {
482 $this->assertRoleAllowsWrites();
484 return $this->__call( __FUNCTION__
, func_get_args() );
487 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
488 $this->assertRoleAllowsWrites();
490 return $this->__call( __FUNCTION__
, func_get_args() );
493 public function upsert(
494 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
496 $this->assertRoleAllowsWrites();
498 return $this->__call( __FUNCTION__
, func_get_args() );
501 public function deleteJoin(
502 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
504 $this->assertRoleAllowsWrites();
506 return $this->__call( __FUNCTION__
, func_get_args() );
509 public function delete( $table, $conds, $fname = __METHOD__
) {
510 $this->assertRoleAllowsWrites();
512 return $this->__call( __FUNCTION__
, func_get_args() );
515 public function insertSelect(
516 $destTable, $srcTable, $varMap, $conds,
517 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
519 $this->assertRoleAllowsWrites();
521 return $this->__call( __FUNCTION__
, func_get_args() );
524 public function unionSupportsOrderAndLimit() {
525 return $this->__call( __FUNCTION__
, func_get_args() );
528 public function unionQueries( $sqls, $all ) {
529 return $this->__call( __FUNCTION__
, func_get_args() );
532 public function unionConditionPermutations(
533 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
534 $options = [], $join_conds = []
536 return $this->__call( __FUNCTION__
, func_get_args() );
539 public function conditional( $cond, $trueVal, $falseVal ) {
540 return $this->__call( __FUNCTION__
, func_get_args() );
543 public function strreplace( $orig, $old, $new ) {
544 return $this->__call( __FUNCTION__
, func_get_args() );
547 public function getServerUptime() {
548 return $this->__call( __FUNCTION__
, func_get_args() );
551 public function wasDeadlock() {
552 return $this->__call( __FUNCTION__
, func_get_args() );
555 public function wasLockTimeout() {
556 return $this->__call( __FUNCTION__
, func_get_args() );
559 public function wasConnectionLoss() {
560 return $this->__call( __FUNCTION__
, func_get_args() );
563 public function wasReadOnlyError() {
564 return $this->__call( __FUNCTION__
, func_get_args() );
567 public function wasErrorReissuable() {
568 return $this->__call( __FUNCTION__
, func_get_args() );
571 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
572 return $this->__call( __FUNCTION__
, func_get_args() );
575 public function getReplicaPos() {
576 return $this->__call( __FUNCTION__
, func_get_args() );
579 public function getMasterPos() {
580 return $this->__call( __FUNCTION__
, func_get_args() );
583 public function serverIsReadOnly() {
584 return $this->__call( __FUNCTION__
, func_get_args() );
587 public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
588 // DB_REPLICA role: caller might want to refresh cache after a REPEATABLE-READ snapshot
589 return $this->__call( __FUNCTION__
, func_get_args() );
592 public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
593 // DB_REPLICA role: caller might want to refresh cache after a REPEATABLE-READ snapshot
594 return $this->__call( __FUNCTION__
, func_get_args() );
597 public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
598 return $this->onTransactionCommitOrIdle( $callback, $fname );
601 public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
602 // DB_REPLICA role: caller might want to refresh cache after a cache mutex is released
603 return $this->__call( __FUNCTION__
, func_get_args() );
606 public function onAtomicSectionCancel( callable
$callback, $fname = __METHOD__
) {
607 return $this->__call( __FUNCTION__
, func_get_args() );
610 public function setTransactionListener( $name, callable
$callback = null ) {
611 return $this->__call( __FUNCTION__
, func_get_args() );
614 public function startAtomic(
615 $fname = __METHOD__
, $cancelable = IDatabase
::ATOMIC_NOT_CANCELABLE
617 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
618 return $this->__call( __FUNCTION__
, func_get_args() );
621 public function endAtomic( $fname = __METHOD__
) {
622 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
623 return $this->__call( __FUNCTION__
, func_get_args() );
626 public function cancelAtomic( $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null ) {
627 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
628 return $this->__call( __FUNCTION__
, func_get_args() );
631 public function doAtomicSection(
632 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
634 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
635 return $this->__call( __FUNCTION__
, func_get_args() );
638 public function begin( $fname = __METHOD__
, $mode = IDatabase
::TRANSACTION_EXPLICIT
) {
639 return $this->__call( __FUNCTION__
, func_get_args() );
642 public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
643 return $this->__call( __FUNCTION__
, func_get_args() );
646 public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
647 return $this->__call( __FUNCTION__
, func_get_args() );
650 public function flushSnapshot( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
651 return $this->__call( __FUNCTION__
, func_get_args() );
654 public function timestamp( $ts = 0 ) {
655 return $this->__call( __FUNCTION__
, func_get_args() );
658 public function timestampOrNull( $ts = null ) {
659 return $this->__call( __FUNCTION__
, func_get_args() );
662 public function ping( &$rtt = null ) {
663 return func_num_args()
664 ?
$this->__call( __FUNCTION__
, [ &$rtt ] )
665 : $this->__call( __FUNCTION__
, [] ); // method cares about null vs missing
668 public function getLag() {
669 return $this->__call( __FUNCTION__
, func_get_args() );
672 public function getSessionLagStatus() {
673 return $this->__call( __FUNCTION__
, func_get_args() );
676 public function maxListLen() {
677 return $this->__call( __FUNCTION__
, func_get_args() );
680 public function encodeBlob( $b ) {
681 return $this->__call( __FUNCTION__
, func_get_args() );
684 public function decodeBlob( $b ) {
685 return $this->__call( __FUNCTION__
, func_get_args() );
688 public function setSessionOptions( array $options ) {
689 return $this->__call( __FUNCTION__
, func_get_args() );
692 public function setSchemaVars( $vars ) {
693 return $this->__call( __FUNCTION__
, func_get_args() );
696 public function lockIsFree( $lockName, $method ) {
697 $this->assertRoleAllowsWrites();
699 return $this->__call( __FUNCTION__
, func_get_args() );
702 public function lock( $lockName, $method, $timeout = 5 ) {
703 $this->assertRoleAllowsWrites();
705 return $this->__call( __FUNCTION__
, func_get_args() );
708 public function unlock( $lockName, $method ) {
709 $this->assertRoleAllowsWrites();
711 return $this->__call( __FUNCTION__
, func_get_args() );
714 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
715 $this->assertRoleAllowsWrites();
717 return $this->__call( __FUNCTION__
, func_get_args() );
720 public function namedLocksEnqueue() {
721 return $this->__call( __FUNCTION__
, func_get_args() );
724 public function getInfinity() {
725 return $this->__call( __FUNCTION__
, func_get_args() );
728 public function encodeExpiry( $expiry ) {
729 return $this->__call( __FUNCTION__
, func_get_args() );
732 public function decodeExpiry( $expiry, $format = TS_MW
) {
733 return $this->__call( __FUNCTION__
, func_get_args() );
736 public function setBigSelects( $value = true ) {
737 return $this->__call( __FUNCTION__
, func_get_args() );
740 public function isReadOnly() {
741 return $this->__call( __FUNCTION__
, func_get_args() );
744 public function setTableAliases( array $aliases ) {
745 return $this->__call( __FUNCTION__
, func_get_args() );
748 public function setIndexAliases( array $aliases ) {
749 return $this->__call( __FUNCTION__
, func_get_args() );
752 public function __toString() {
753 if ( $this->conn
=== null ) {
754 // spl_object_id is PHP >= 7.2
755 $id = function_exists( 'spl_object_id' )
756 ?
spl_object_id( $this )
757 : spl_object_hash( $this );
759 return $this->getType() . ' object #' . $id;
762 return $this->__call( __FUNCTION__
, func_get_args() );
766 * Error out if the role is not DB_MASTER
768 * Note that the underlying connection may or may not itself be read-only.
769 * It could even be to a writable master (both server-side and to the application).
770 * This error is meant for the case when a DB_REPLICA handle was requested but a
771 * a write was attempted on that handle regardless.
773 * In configurations where the master DB has some generic read load or is the only server,
774 * DB_MASTER/DB_REPLICA will sometimes (or always) use the same connection to the master DB.
775 * This does not effect the role of DBConnRef instances.
776 * @throws DBReadOnlyRoleError
778 protected function assertRoleAllowsWrites() {
779 // DB_MASTER is "prima facie" writable
780 if ( $this->role
!== ILoadBalancer
::DB_MASTER
) {
781 throw new DBReadOnlyRoleError( $this->conn
, "Cannot write with role DB_REPLICA" );
786 * Clean up the connection when out of scope
788 function __destruct() {
790 $this->lb
->reuseConnection( $this->conn
);
797 * @deprecated since 1.29
799 class_alias( DBConnRef
::class, 'DBConnRef' );